<template>
  <div class="container">
    <navigate>家庭访谈</navigate>

    <div class="title flex_align_center flex_row">
      <div class="bar"></div>
      <div class="text">经济及教育子女情况</div>
    </div>
    <div class="card_questionnaire">
      <div class="item" v-for="(item, index) in list" :key="index">
        <div :class="['question', { type2: item.opition_type == 2 }]">
          {{ item.name }}
        </div>
        <textarea
          placeholder="请输入实际情况"
          class="textarea"
          v-model="item.val"
          v-if="item.opition_type == 2"
        ></textarea>
        <template v-else>
          <v-radio
            class="type2"
            v-for="(e, i) in item.templateOptions"
            :key="i"
            @selected="item.val.id = $event"
            :val="e.id"
            v-model="item.val.id"
            :idText="'text' + i + index"
            :name="`name${index}`"
            :text="e.name"
          ></v-radio>
        </template>
      </div>
    </div>

    <div class="title flex_align_center flex_row">
      <div class="bar"></div>
      <div class="text">生活习惯与能力</div>
    </div>

    <div class="card_mental_state">
      <template v-for="(item, i) in list2">
        <van-cell-group
          v-if="item.opition_type == 1"
          class="nowrap input_outer father_relative"
          :key="i + '_'"
        >
          <van-field
            readonly
            clickable
            v-model="item.val.name"
            :label="item.name"
            placeholder="请选择"
            @click="item.visible = true"
          />
          <v-picker
            :columns="item.templateOptions"
            valueKey="name"
            @confirm="
              item.val = $event;
              item.visible = false;
            "
            :isVisible="item.visible"
            @cancel="item.visible = false"
          />
          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>

        <van-cell-group
          :key="i + '-++'"
          class="input_outer"
          v-else-if="item.opition_type == 2"
        >
          <van-field
            v-model="item.val"
            :label="item.name"
            placeholder="请输入"
          />
        </van-cell-group>
      </template>
    </div>

    <div class="title flex_align_center flex_row">
      <div class="bar"></div>
      <div class="text">居住环境</div>
    </div>

    <div class="card_mental_state">
      <template v-for="(item, i) in list3">
        <van-cell-group
          v-if="item.opition_type == 1"
          class="nowrap input_outer father_relative"
          :key="i + '_'"
        >
          <van-field
            readonly
            clickable
            v-model="item.val.name"
            :label="item.name"
            placeholder="请选择"
            @click="item.visible = true"
          />
          <v-picker
            :columns="item.templateOptions"
            valueKey="name"
            @confirm="
              item.val = $event;
              item.visible = false;
            "
            :isVisible="item.visible"
            @cancel="item.visible = false"
          />
          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>

        <van-cell-group
          :key="i + '-++'"
          class="input_outer"
          v-else-if="item.opition_type == 2"
        >
          <van-field
            v-model="item.val"
            :label="item.name"
            placeholder="请输入"
          />
        </van-cell-group>
      </template>
    </div>

    <button class="btn" @click="save">保存资料</button>
  </div>
</template>

<script>
import {
  getTemplateList,
  submitSelfAssessment,
  queryArchivesResults,
} from "@/api/funcation/selfAssessment";
import { mapState } from "vuex";

export default {
  data() {
    return {
      list: [], // 经济及教育子女情况
      list2: [], // 生活习惯与能力
      list3: [], // 居住环境
      resultData: [], // 结果数据
      userArchivesResults: [], // 档案结果缓存
    };
  },
  computed: {
    ...mapState(["INFO"]), // 从Vuex获取用户信息
  },
  async created() {
    // 先获取模板数据，再加载档案结果
    await this.getTemplateList();
    await this.getArchivesResults();
  },
  methods: {
    /**
     * 获取模板数据（初始化表单结构）
     */
    async getTemplateList() {
      try {
        const { data } = await getTemplateList({ id: 6 });
        // 初始化三个列表的数据结构
        this.list = data[0]?.templates[0]?.children || [];
        this.list2 = data[0]?.templates[1]?.children || [];
        this.list3 = data[0]?.templates[2]?.children || [];

        // 初始化list（经济及教育子女情况）
        this.list.forEach((item) => {
          this.$set(
            item,
            "val",
            item.opition_type === 1 ? { id: null, name: "" } : ""
          );
        });

        // 初始化list2（生活习惯与能力）
        this.list2.forEach((item) => {
          this.$set(item, "visible", false); // 选择器显示状态
          this.$set(
            item,
            "val",
            item.opition_type === 1 ? { id: null, name: "" } : ""
          );
        });

        // 初始化list3（居住环境）
        this.list3.forEach((item) => {
          this.$set(item, "visible", false); // 选择器显示状态
          this.$set(
            item,
            "val",
            item.opition_type === 1 ? { id: null, name: "" } : ""
          );
        });
      } catch (error) {}
    },

    /**
     * 获取历史档案结果（回显数据）
     */
    async getArchivesResults() {
      try {
        const par = {
          user_id: this.INFO?.id, // 增加用户ID存在性判断
          type_id: 6,
        };
        const res = await queryArchivesResults(par);

        if (res.code === 200 && res.data?.length) {
          // 安全解析content（防止空数据）
          this.userArchivesResults = JSON.parse(res.data[0].content || "[]");

          if (this.userArchivesResults.length) {
            const combinedList = [...this.list, ...this.list2, ...this.list3];
            this.userArchivesResults.forEach(({ questionId, answersId }) => {
              // 查找对应的问题项
              const item = combinedList.find(
                (item) => item.id === Number(questionId)
              );
              if (!item || answersId === undefined) return;

              // 根据问题类型设置值（确保类型匹配）
              if (item.opition_type === 1) {
                // 选项类型：从模板选项中匹配对应值
                const option = item.templateOptions?.find(
                  (opt) => opt.id === answersId
                );
                if (option) {
                  this.$set(item, "val", option);
                }
              } else if (item.opition_type === 2) {
                // 文本类型：直接赋值
                this.$set(item, "val", answersId);
              }
            });
          }
        }
      } catch (error) {
        console.error("获取档案结果失败:", error);
      }
    },

    /**
     * 保存表单数据
     */
    async save() {
      try {
        const combinedList = [...this.list, ...this.list2, ...this.list3];
        const idPairs = combinedList.map((item) => ({
          questionId: item.id,
          // 安全获取answersId：处理undefined和空对象情况
          answersId:
            typeof item.val === "object"
              ? item.val?.id ?? null // 对象类型取id，默认null
              : item.val || "", // 文本类型直接取val，默认空字符串
        }));

        const params = {
          user_id: this.INFO?.id || "", // 防止用户信息不存在
          content: JSON.stringify(idPairs),
          type_id: 6,
          source: 1,
        };

        const res = await submitSelfAssessment(params);
        if (res.code === 200) {
          this.$toast.success("修改成功！");
        } else {
          this.$toast.fail("保存失败，请重试");
        }
      } catch (error) {
        console.error("保存数据失败:", error);
        this.$toast.fail("保存出错，请稍后再试");
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
@import "../styles/common.less";
</style>
